#include <jni.h>
#include <string>
#include <dlfcn.h>
#include <android/log.h>
#include <unistd.h>
#include "webrtc_interface.h"

#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, "TRY_WEBRTC", ##__VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, "TRY_WEBRTC", ##__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, "TRY_WEBRTC", ##__VA_ARGS__)

extern "C" JNIEXPORT jstring JNICALL
Java_cn_hdcon_hdrtc_RTCHelper_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

class WebrtcClientCallbackImpl : public WebrtcClientCallback {
public:
    WebrtcClientCallbackImpl() {}
    virtual ~WebrtcClientCallbackImpl() {}
    virtual void *OnAllocWnd(int wnd_id = 0) override { return NULL;};
    virtual void OnFreeWnd(void *wnd) override {};
    virtual void OnClientStatus(WebrtcClientStatus_t stat, const char *reason) override {
        std::string lo = reason;
        LOGI("Msg Recived %s",reason);

        //LOGI(lo.c_str());
    };
    virtual void OnRemoteMediaConfig(RtcAudioConfig_t *a_cfg, RtcVideoConfig_t *v_cfg) override {};
    virtual void OnLogMessage(const char* message)override {}

protected:
};

WebrtcClientCallbackImpl wc_cb;
 void showSDKMessage(char* message){

//    jclass cls_util = env->FindClass("cn/hdcon/hdrtc/RTCHelper");   //注意，这里的使用的斜杠而不是点
//    if(cls_util == NULL){
//        return ;
//    }
//
//    /**
//    *获取静态方法操作的对象 ，参数分别是 jclass,方法名称，方法签名
//    */
//    jmethodID mtd_static_method = env->GetStaticMethodID(cls_util,"showMessage","(Ljava/lang/String;)V");
//    if(mtd_static_method == NULL){
//        return ;
//    }
//
//    jstring data = env->NewStringUTF(message);
//    if(data == NULL){
//        return ;
//    }
//
//    /**
//    *调用方法，参数是 jclass，jmethodID，传递的参数
//    */
//    env->CallStaticVoidMethod(cls_util,mtd_static_method,data);
//
//    //删除引用
//    env->DeleteLocalRef(cls_util);
//    env->DeleteLocalRef(reinterpret_cast<jobject>(mtd_static_method));
//    env->DeleteLocalRef(data);

}
WebrtcInterface* rtc;
//char *getMyString();
jstring charTojstring(JNIEnv* env, const char* pat) {
    //定义java String类 strClass
    jclass strClass = (env)->FindClass("Ljava/lang/String;");
    //获取String(byte[],String)的构造器,用于将本地byte[]数组转换为一个新String
    jmethodID ctorID = (env)->GetMethodID(strClass, "<init>", "([BLjava/lang/String;)V");
    //建立byte数组
    jbyteArray bytes = (env)->NewByteArray(strlen(pat));
    //将char* 转换为byte数组
    (env)->SetByteArrayRegion(bytes, 0, strlen(pat), (jbyte*) pat);
    // 设置String, 保存语言类型,用于byte数组转换至String时的参数
    jstring encoding = (env)->NewStringUTF("GB2312");
    //将byte数组转换为java String,并输出
    return (jstring) (env)->NewObject(strClass, ctorID, bytes, encoding);
}

char* jstringToChar(JNIEnv* env, jstring jstr) {
    char* rtn = NULL;
    jclass clsstring = env->FindClass("java/lang/String");
    jstring strencode = env->NewStringUTF("GB2312");
    jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B");
    jbyteArray barr = (jbyteArray) env->CallObjectMethod(jstr, mid, strencode);
    jsize alen = env->GetArrayLength(barr);
    jbyte* ba = env->GetByteArrayElements(barr, JNI_FALSE);
    if (alen > 0) {
        rtn = (char*) malloc(alen + 1);
        memcpy(rtn, ba, alen);
        rtn[alen] = 0;
    }
    env->ReleaseByteArrayElements(barr, ba, 0);
    return rtn;
}
extern "C" JNIEXPORT jstring JNICALL
Java_cn_hdcon_hdrtc_RTCHelper_loginJNI(
        JNIEnv* env,
        jobject /* this */,jstring username,jstring password,jstring server,jint port,jint localport) {

    LOGI("test start");

    rtc = CreateWebrtcInterface(&wc_cb, NULL);
    RtcSipConfig_t config;
    config.username =  jstringToChar(env, username);
    config.pwd = jstringToChar(env, password);
    config.server_ip = jstringToChar(env, server);
    config.server_port = port;
    config.local_ip = "0.0.0.0";
    config.local_port = 5060;
    rtc->Login(config);
    LOGI("test end");
    std::string hello = "test12345";//getMyString();
    return env->NewStringUTF(hello.c_str());
}
extern "C" JNIEXPORT jstring JNICALL
Java_cn_hdcon_hdrtc_RTCHelper_logoutJNI(
        JNIEnv* env,
        jobject /* this */){
        rtc->Logout();
}